package com.platform.service;

import com.platform.cache.CacheUtil;
import com.platform.dao.SysMacroDao;
import com.platform.entity.SysMacroEntity;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 通用字典表Service接口
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017-08-22 11:48:16
 */
@Service("sysMacroService")
public class SysMacroService implements  InitializingBean{
    @Autowired
    private SysMacroDao sysMacroDao;
    
    public void afterPropertiesSet() throws Exception {
        init();
    }
    
    public void init() {
    	Map<String,Object> params = new HashMap<String, Object>();
    	params.put("type", "0");
    	List<SysMacroEntity> sysMacroCatalogs = sysMacroDao.queryList(params);
    	params.put("type", "1");
    	List<SysMacroEntity> sysMacroValues = sysMacroDao.queryList(params);
    	CacheUtil.init(sysMacroCatalogs, sysMacroValues);
    }
    
    public SysMacroEntity queryObject(Long macroId) {
        return sysMacroDao.queryObject(macroId);
    }

    public List<SysMacroEntity> queryList(Map<String, Object> map) {
        return sysMacroDao.queryList(map);
    }

    public int queryTotal(Map<String, Object> map) {
        return sysMacroDao.queryTotal(map);
    }

    public int save(SysMacroEntity sysMacro) {
        sysMacro.setGmtCreate(new Date());
        sysMacroDao.save(sysMacro);
        updateCache(sysMacro);
        return 1;
    }

    public void updateCache(SysMacroEntity sysMacro) {
        if(sysMacro.getParentId() != null) {
        	SysMacroEntity parent = sysMacroDao.queryObject(sysMacro.getParentId());
        	if(parent != null) {
        		Map<String,Object> params = new HashMap<String,Object>();
        		params.put("parentId", sysMacro.getParentId());
                CacheUtil.update(parent.getValue(), queryList(params));
        	}
        }
    }
    
    public int update(SysMacroEntity sysMacro) {
        sysMacro.setGmtModified(new Date());
        sysMacroDao.update(sysMacro);
        updateCache(sysMacro);
        return 1;
    }

    public int delete(Long macroId) {
    	SysMacroEntity sysMacro = sysMacroDao.queryObject(macroId);
        sysMacroDao.delete(macroId);
        updateCache(sysMacro);
        return 1;
    }

    public int deleteBatch(Long[] macroIds) {
        sysMacroDao.deleteBatch(macroIds);
        init();
        return 1;
    }

    public List<SysMacroEntity> queryMacrosByValue(String value) {
        return sysMacroDao.queryMacrosByValue(value);
    }
}
